<template>
  <div class="communication-center">
    <!-- 页面头部 -->
    <div class="communication-header">
      <h1>交流中心</h1>
    </div>

    <!-- 主要内容区域 -->
    <div class="communication-content">
      <!-- 左侧问题列表区域 -->
      <div class="main-content">
        <!-- 操作栏 -->
        <div class="action-bar">
          <div class="filter-section">
            <span class="filter-label">问题类型：</span>
            <a-radio-group v-model="filterType" type="button" @change="handleFilterChange">
              <a-radio value="all">全部</a-radio>
              <a-radio value="技术">技术</a-radio>
              <a-radio value="学习">学习</a-radio>
              <a-radio value="生活">生活</a-radio>
              <a-radio value="其他">其他</a-radio>
            </a-radio-group>
          </div>
          <div class="search-section">
            <a-input-search 
              v-model="searchKeyword" 
              placeholder="搜索问题标题"
              :loading="loading"
              @search="handleSearch"
              @clear="handleSearchClear"
              allow-clear
              style="width: 300px"
            />
          </div>
        </div>

        <!-- 问题列表 -->
        <div class="question-list">
          <a-spin :loading="loading" style="width: 100%">
            <a-empty v-if="questions.length === 0 && !loading" description="暂无问题">
              <template #extra>
                <a-button type="primary" @click="createQuestion">发布第一个问题</a-button>
              </template>
            </a-empty>
            
            <div v-else class="question-items">
              <div
                v-for="question in questions"
                :key="question.questionIdStr || question.questionId"
                class="question-card"
                @click="viewQuestionDetail(question.questionIdStr || question.questionId)"
              >
                <div class="question-header">
                  <div class="question-title">
                    <h3>{{ question.title }}</h3>
                    <a-tag :color="getQuestionTypeColor(question.questionType)" size="small">
                      {{ question.questionType }}
                    </a-tag>
                  </div>
                  <div class="question-meta">
                    <span class="author">
                      <icon-user />
                      {{ question.author?.nickname || '匿名用户' }}
                    </span>
                    <span class="time">
                      <icon-clock-circle />
                      {{ formatTime(question.publishTime) }}
                    </span>
                  </div>
                </div>
                
                <div class="question-content">
                  <p>{{ question.content }}</p>
                </div>
                
                <div class="question-footer">
                  <div class="question-stats">
                    <span class="stat-item">
                      <icon-like />
                      {{ question.likeCount || 0 }}
                    </span>
                    <span class="stat-item">
                      <icon-message />
                      {{ question.answerCount || 0 }}
                    </span>
                    <span class="stat-item">
                      <icon-eye />
                      {{ question.viewCount || 0 }}
                    </span>
                  </div>
                  <a-button type="outline" size="mini" @click.stop="viewQuestionDetail(question.questionIdStr || question.questionId)">
                    查看详情
                  </a-button>
                </div>
              </div>
            </div>
          </a-spin>
          
          <!-- 分页 -->
          <div v-if="total > 0" class="pagination-section">
            <div class="pagination-controls">
              <div class="page-size-selector">
                <span class="page-size-label">每页显示：</span>
                <a-select 
                  v-model="pageSize" 
                  :style="{ width: '100px' }"
                  @change="handlePageSizeChange"
                >
                  <a-option :value="5">5条</a-option>
                  <a-option :value="10">10条</a-option>
                  <a-option :value="20">20条</a-option>
                  <a-option :value="50">50条</a-option>
                </a-select>
              </div>
              <a-pagination 
                v-model:current="pageNum" 
                :total="total" 
                :page-size="pageSize"
                show-total
                show-jumper
                show-page-size
                @change="handlePageChange"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧边栏 -->
      <div class="sidebar">
        <!-- 快速操作 -->
        <div class="sidebar-card">
          <div class="card-header">
            <h3>快速操作</h3>
          </div>
          <div class="card-content">
            <a-button type="primary" long @click="createQuestion" style="margin-bottom: 12px;">
              <template #icon>
                <icon-plus />
              </template>
              发布新问题
            </a-button>
            <a-button type="outline" long @click="viewAllQuestions">
              <template #icon>
                <icon-list />
              </template>
              查看所有问题
            </a-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 发布问题模态框 -->
    <a-modal 
      v-model:visible="questionModalVisible" 
      title="发布问题"
      :footer="false"
      width="600px"
    >
      <a-form :model="questionForm" layout="vertical">
        <a-form-item field="title" label="问题标题" :rules="[{ required: true, message: '请输入问题标题' }]">
          <a-input 
            v-model="questionForm.title" 
            placeholder="请输入问题标题"
            :max-length="100"
            show-word-limit
          />
        </a-form-item>
        
        <a-form-item field="questionType" label="问题类型" :rules="[{ required: true, message: '请选择问题类型' }]">
          <a-select 
            v-model="questionForm.questionType" 
            placeholder="请选择问题类型"
          >
            <a-option value="技术">技术</a-option>
            <a-option value="学习">学习</a-option>
            <a-option value="生活">生活</a-option>
            <a-option value="其他">其他</a-option>
          </a-select>
        </a-form-item>
        
        <a-form-item field="content" label="问题描述" :rules="[{ required: true, message: '请输入问题描述' }]">
          <a-textarea 
            v-model="questionForm.content" 
            placeholder="请输入详细的问题描述"
            :rows="6"
            :max-length="1000"
            show-word-limit
          />
        </a-form-item>
        
        <div class="modal-footer">
          <a-button @click="cancelQuestion">取消</a-button>
          <a-button 
            type="primary" 
            :loading="submitting" 
            @click="submitQuestion"
            :disabled="!isFormValid"
          >
            发布问题
          </a-button>
        </div>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Message } from '@arco-design/web-vue';
import { questionApi } from '@/api/question';

const router = useRouter();
const loading = ref(false);
const submitting = ref(false);
const questions = ref([]);
const filterType = ref('all');
const searchKeyword = ref('');
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);
const questionModalVisible = ref(false);

const questionForm = reactive({
  title: '',
  questionType: '',
  content: ''
});

const isFormValid = computed(() => {
  return questionForm.title && questionForm.questionType && questionForm.content;
});

// 获取问题列表
const fetchQuestions = async () => {
  loading.value = true;
  try {
    const res = await questionApi.getQuestionList({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      questionType: filterType.value !== 'all' ? filterType.value : undefined,
      keyword: searchKeyword.value || undefined
    });
    
    if (res.data.success) {
      questions.value = res.data.list || res.data.data || [];
      total.value = res.data.total || 0;
    } else {
      Message.error('获取问题列表失败');
      questions.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取问题列表失败', error);
    Message.error('获取问题列表失败，请重试');
    questions.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 处理过滤器变更
const handleFilterChange = (value) => {
  filterType.value = value;
  pageNum.value = 1;
  fetchQuestions();
};

// 处理搜索
const handleSearch = () => {
  pageNum.value = 1;
  fetchQuestions();
};

// 处理搜索清除
const handleSearchClear = () => {
  searchKeyword.value = '';
  pageNum.value = 1;
  fetchQuestions();
};

// 处理分页变更
const handlePageChange = (page) => {
  pageNum.value = page;
  fetchQuestions();
};

// 处理页面大小变更
const handlePageSizeChange = (size) => {
  pageSize.value = size;
  pageNum.value = 1; // 重置到第一页
  fetchQuestions();
};

// 创建问题
const createQuestion = () => {
  questionModalVisible.value = true;
};

// 提交问题
const submitQuestion = async () => {
  if (!isFormValid.value) {
    Message.warning('请填写完整的问题信息');
    return;
  }
  
  submitting.value = true;
  try {
    const res = await questionApi.createQuestion(questionForm);
    if (res.data.success) {
      Message.success('问题发布成功');
      questionModalVisible.value = false;
      resetQuestionForm();
      fetchQuestions();
    } else {
      Message.error(res.data.message || '发布问题失败');
    }
  } catch (error) {
    console.error('发布问题失败', error);
    Message.error('发布问题失败，请重试');
  } finally {
    submitting.value = false;
  }
};

// 取消问题
const cancelQuestion = () => {
  questionModalVisible.value = false;
  resetQuestionForm();
};

// 重置问题表单
const resetQuestionForm = () => {
  questionForm.title = '';
  questionForm.questionType = '';
  questionForm.content = '';
};

// 查看问题详情
const viewQuestionDetail = (questionId) => {
  // 将questionId转换为字符串，避免JavaScript大整数精度问题
  router.push(`/communication/question/${String(questionId)}`);
};

// 查看所有问题
const viewAllQuestions = () => {
  filterType.value = 'all';
  pageNum.value = 1;
  fetchQuestions();
};

// 获取问题类型颜色
const getQuestionTypeColor = (type) => {
  const colorMap = {
    '技术': 'blue',
    '学习': 'green',
    '生活': 'orange',
    '其他': 'purple'
  };
  return colorMap[type] || 'gray';
};

// 格式化时间
const formatTime = (time) => {
  if (!time) return '';
  
  const date = new Date(time);
  const now = new Date();
  const diff = now - date;
  
  if (diff < 60000) return '刚刚';
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`;
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`;
  if (diff < 2592000000) return `${Math.floor(diff / 86400000)}天前`;
  
  return date.toLocaleDateString();
};

// 页面加载时初始化数据
onMounted(() => {
  fetchQuestions();
});
</script>

<style scoped lang="less">
.communication-center {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  min-height: calc(100vh - 64px);
  background: var(--color-bg-1);
  
  .communication-header {
    margin-bottom: 30px;
    text-align: center;
    
    h1 {
      font-size: 32px;
      font-weight: 600;
      margin-bottom: 8px;
      color: var(--color-text-1);
    }
  }
  
  .communication-content {
    display: grid;
    grid-template-columns: 1fr 300px;
    gap: 24px;
    align-items: start;
  }
  
  .main-content {
    .action-bar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding: 16px;
        background: var(--color-bg-1);
        border-radius: 6px;
        border: 1px solid var(--color-border-2);
        box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
        
        .filter-section {
          display: flex;
          align-items: center;
          gap: 12px;
          
          .filter-label {
            color: var(--color-text-2);
            font-size: 14px;
          }
        }
        
        .search-section {
          display: flex;
          align-items: center;
        }
      }
    
    .question-list {
      .question-items {
        display: flex;
        flex-direction: column;
        gap: 16px;
      }
      
      .question-card {
        padding: 20px;
        background: var(--color-bg-1);
        border-radius: 6px;
        border: 1px solid var(--color-border-2);
        cursor: pointer;
        transition: all 0.3s;
        box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
        
        &:hover {
          box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
        }
        
        .question-header {
          margin-bottom: 12px;
          
          .question-title {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 8px;
            
            h3 {
              font-size: 18px;
              font-weight: 600;
              color: var(--color-text-1);
              margin: 0;
              flex: 1;
              margin-right: 12px;
            }
          }
          
          .question-meta {
            display: flex;
            gap: 16px;
            font-size: 12px;
            color: var(--color-text-3);
            
            .author, .time {
              display: flex;
              align-items: center;
              gap: 4px;
            }
          }
        }
        
        .question-content {
          margin-bottom: 16px;
          
          p {
            color: var(--color-text-2);
            line-height: 1.6;
            margin: 0;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
            overflow: hidden;
          }
        }
        
        .question-footer {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .question-stats {
            display: flex;
            gap: 16px;
            
            .stat-item {
              display: flex;
              align-items: center;
              gap: 4px;
              font-size: 12px;
              color: var(--color-text-3);
            }
          }
        }
      }
      
      .pagination-section {
        margin-top: 24px;
        
        .pagination-controls {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .page-size-selector {
            display: flex;
            align-items: center;
            gap: 8px;
            
            .page-size-label {
              color: var(--color-text-2);
              font-size: 14px;
            }
          }
        }
      }
    }
  }
  
  .sidebar {
    display: flex;
    flex-direction: column;
    gap: 20px;
    
    .sidebar-card {
      background: var(--color-bg-1);
      border-radius: 6px;
      border: 1px solid var(--color-border-2);
      overflow: hidden;
      box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px;
        background: var(--color-bg-1);
        border-bottom: 1px solid var(--color-border-2);
        
        h3 {
          font-size: 16px;
          font-weight: 600;
          color: var(--color-text-1);
          margin: 0;
        }
      }
      
      .card-content {
        padding: 16px;
        
        .my-questions {
          .my-question-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px solid var(--color-border-1);
            cursor: pointer;
            transition: color 0.3s;
            
            &:last-child {
              border-bottom: none;
            }
            
            &:hover {
              color: var(--color-text-1);
            }
            
            .question-title {
              flex: 1;
              font-size: 14px;
              color: var(--color-text-2);
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              margin-right: 8px;
            }
            
            .question-time {
              font-size: 12px;
              color: var(--color-text-3);
            }
          }
        }
        
        .leaderboard {
          .leaderboard-item {
            display: flex;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid var(--color-border-1);
            
            &:last-child {
              border-bottom: none;
            }
            
            .rank {
              margin-right: 12px;
              
              .rank-number {
                display: flex;
                align-items: center;
                justify-content: center;
                width: 24px;
                height: 24px;
                border-radius: 50%;
                background: var(--color-fill-3);
                font-size: 12px;
                font-weight: 600;
                color: var(--color-text-2);
                
                &.top-3 {
                  background: var(--color-fill-3);
                  color: var(--color-text-2);
                }
              }
            }
            
            .user-info {
              display: flex;
              align-items: center;
              flex: 1;
              
              .user-details {
                margin-left: 8px;
                
                .username {
                  display: block;
                  font-size: 14px;
                  font-weight: 500;
                  color: var(--color-text-1);
                }
                
                .user-stats {
                  font-size: 12px;
                  color: var(--color-text-3);
                }
              }
            }
          }
        }
      }
    }
  }
  
  .modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    margin-top: 20px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .communication-center {
    padding: 16px;
    
    .communication-content {
      grid-template-columns: 1fr;
      gap: 16px;
    }
    
    .action-bar {
      flex-direction: column;
      gap: 16px;
      align-items: stretch;
    }
  }
}
</style>